<template>
    <div class="business-container">
        <el-form :model="form" :inline="true">
            <el-form-item label="客户姓名">
                <el-input v-model="form.name" placeholder="请输入客户姓名" clearable />
            </el-form-item>
            <el-form-item label="客户手机">
                <el-input v-model="form.phone" placeholder="请输入客户手机号码" clearable />
            </el-form-item>
            <el-form-item label="归属人">
                <el-input v-model="form.owner" placeholder="请输入商机归属人" clearable />
            </el-form-item>
            <el-form-item label="跟进时间">
                <el-date-picker v-model="form.dateRange" type="datetimerange" start-placeholder="开始日期"
                    end-placeholder="结束日期" value-format="YYYY-MM-DD" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="getTable">搜索</el-button>
                <el-button :icon="Refresh" @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>
        <div>
            <el-button type="primary" :icon="Plus" plain @click="addopen">新增</el-button>
            <el-button type="success" :icon="Edit" plain :disabled="selectedRows.length !== 1" @click="updateGet">修改</el-button>
            <el-button type="danger" :icon="Delete" plain :disabled="selectedRows.length === 0" @click="deleteGet">删除</el-button>
            <el-button type="warning" :icon="Download" plain @click="handleExport">导出</el-button>
        </div>
        <el-table :data="tableData" style="width: 100%; margin-top: 20px;" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column prop="name" label="客户姓名" align="center" width="118" />
            <el-table-column prop="phone" label="手机号码" align="center" width="118" />
            <el-table-column prop="owner" label="商机归属" align="center" width="118" />
            <el-table-column prop="createTime" label="创建时间" align="center" />
            <el-table-column prop="status" label="商机状态" align="center" width="120">
                <template #default="scope">
                    <el-tag type="primary">{{ getStatusLabel(scope.row.status) }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="nextTime" label="下次跟进时间" align="center" />
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button type="primary" text :icon="View" style="padding: 0;"
                        @click="golook(scope.row.businessId)">
                        查看
                    </el-button>
                    <el-button
                        type="primary"
                        text
                        :icon="Pointer"
                        style="padding: 0; margin-left: 12px;"
                        @click="openAssignDialog(scope.row)"
                    >
                        分配
                    </el-button>
                    <el-button
                        v-if="scope.row.owner === username"
                        type="primary"
                        text
                        :icon="TopRight"
                        style="padding: 0; margin-left: 12px;"
                        @click="golook2(scope.row.businessId)"
                    >
                        跟进
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background layout=" ->,total, sizes, prev, pager, next, jumper" :total="total"
            :page-size="pageSize" :current-page="pageNum" :page-sizes="[10, 20, 30, 50]" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" style="margin-top: 16px; text-align: right;" />
        <el-dialog v-model="dialogVisible" title="添加线索" width="750">
            <div>
                <el-form :model="dialogfrom" class="dialog-form" label-width="100px" ref="diaLogFromRef" :rules="rules">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="手机号码：" prop="phone">
                                <el-input v-model="dialogfrom.phone" placeholder="请输入手机号码" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="客户姓名：" prop="name">
                                <el-input v-model="dialogfrom.name" placeholder="请输入客户姓名" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="渠道来源：" prop="channelId">
                                <el-select @change="pitchon" style="width: 100%;" v-model="dialogfrom.channelId"
                                    placeholder="渠道来源" clearable>
                                    <el-option v-for="(item, index) in channlist" :key="index" :label="item.channelName"
                                        :value="item.channelId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="活动信息：" prop="activityId">
                                <el-select style="width: 100%;" v-model="dialogfrom.activityId" placeholder="活动信息"
                                    clearable>
                                    <el-option v-for="(item, index) in activityList" :key="index" :label="item.name"
                                        :value="item.activityId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="客户性别：">
                                <el-radio-group style="width: 100%;" v-model="dialogfrom.gender">
                                    <el-radio :value="0">男</el-radio>
                                    <el-radio :value="1">女</el-radio>
                                    <el-radio :value="2">未知</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="客户年龄：" prop="age">
                                <el-input-number placeholder="年龄" v-model="dialogfrom.age" :min="1" :max="100"
                                    style="width: 100%;" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="微信号：" prop="weixin">
                                <el-input v-model="dialogfrom.weixin" placeholder="请输入微信号" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="QQ号：" prop="qq">
                                <el-input v-model="dialogfrom.qq" placeholder="请输入QQ号" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary"
                        @click="state == true ? submitForm(diaLogFromRef) : updateput(diaLogFromRef)">
                        确定
                    </el-button>
                    <el-button @click="reset(diaLogFromRef)">取消</el-button>

                </span>
            </template>
        </el-dialog>
        <el-dialog v-model="assignDialogVisible" title="分配商机" width="700px">
            <el-form :model="assignForm" :rules="assignRules" ref="assignFormRef" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="归属部门" prop="departmentId" required>
                            <el-tree-select
                                v-model="assignForm.departmentId"
                                :data="deptTree"
                                :props="deptTreeProps"
                                placeholder="请选择归属部门"
                                check-strictly
                                style="width: 100%;"
                                clearable
                                @change="handleDeptChange"  
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="分配给" prop="userId" required>
                            <el-select v-model="assignForm.userId" placeholder="选择用户" filterable @change="handleUserChange">
                                <el-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button type="primary" @click="handleAssign">确定</el-button>
                <el-button @click="assignDialogVisible = false">取消</el-button>
            </template>
        </el-dialog>
    </div>

</template>

<script setup lang="ts">
import request from '../../../utils/request'
import { ref, onMounted, reactive } from 'vue'
import { Search, Refresh, Plus, Edit, Delete, Download, View, Pointer, TopRight } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import Cookies from 'js-cookie'
import { saveAs } from 'file-saver'

const $router = useRouter()

onMounted(async () => {
    await getstatus()
    getTable()
    getchannel()
})

const form = ref({
    name: '',
    phone: '',
    owner: '',
    dateRange: []
})
const tableData = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const statusOptions = ref([])
const selectedRows = ref([])

const username = Cookies.get('username') || ''

const getTable = () => {
    const params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        name: form.value.name || '',
        phone: form.value.phone || '',
        owner: form.value.owner || '',
        'dateRange[0]': form.value.dateRange[0] || '',
        'dateRange[1]': form.value.dateRange[1] || ''
    }
    request('tienchin/business/list', { params }).then((res: any) => {
        const rows = (res.rows || []).map(item => ({
            ...item,
            createTime: item.createTime ? item.createTime.replace('T', ' ') : '',
            nextTime: item.nextTime ? item.nextTime.replace('T', ' ') : ''
        }))
        tableData.value = rows
        total.value = res.total
    })
}

const getStatusLabel = (value) => {
    const option = statusOptions.value.find(item => String(item.dictValue) === String(value))
    return option ? option.dictLabel : value
}

const resetForm = () => {
    form.value = {
        name: '',
        phone: '',
        owner: '',
        dateRange: []
    }
    getTable()
}

const getstatus = () => {
    request("system/dict/data/type/business_status").then((res) => {
        statusOptions.value = res.data
    })
}
// 查看
const golook = (id) => {
    console.log(id);
    $router.push({
        path: `/business/details/index/${id}/view`,
    })
}
const golook2 = (id) => {
    console.log(id);
    $router.push({
        path: `/business/details/index/${id}/follow`,
    })
}

// 弹窗相关
const dialogVisible = ref(false)
const dialogfrom = ref({
    phone: '',
    name: '',
    channelId: null,
    gender: null,
    age: null,
    activityId: null,
    qq: '',
    weixin: '',
})
const businessId = ref(null)
const diaLogFromRef = ref<FormInstance>()
const dellist = ref([])

// const channlist = ref([])
const channlist = ref<{ channelName: string; channelId: number }[]>([])
// 渠道数据接口
const getchannel = () => {
    request('tienchin/business/channels').then(res => {
        channlist.value = res.data
    })
}
// 当前选的年龄
const handleChange = (value: number) => {
    console.log(value)
}
// 当前选的渠道的活动
// const activityList = ref([])
const activityList = ref<{ name: string; activityId: number }[]>([])

// 表单验证
const rules = reactive<FormRules<any>>({
    phone: [
        { required: true, message: '手机号码不能为空', trigger: 'blur' },
        { min: 5, max: 11, message: '请输入正确的号码', trigger: 'blur' },

    ],
    name: [
        { required: true, message: '客户姓名不能为空', trigger: 'blur' },

    ]
})

// 新增点击确定
const submitForm = async (formEl: FormInstance | undefined) => {

    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(dialogfrom.value);
            request({
                url: '/tienchin/business',
                method: 'post',
                data: dialogfrom.value
            }).then(res => {
                console.log(res);
                dialogVisible.value = false
                ElMessage({
                    message: '新增商机成功',
                    type: 'success',
                })
                getTable()
            })
        }
    })
}

const addopen = () => {
    dialogVisible.value = true
    state.value = true
}
// 点击取消
const reset = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    dialogVisible.value = false
}
const state = ref(true)
const pitchon = (e: number) => {
    request({
        url: '/tienchin/clue/activity/' + e,
        method: 'get'
    }).then(res => {
        console.log(res);
        dialogfrom.value.activityId = null
        activityList.value = res.data
    })

}
// 修改按钮事件
const updateGet = () => {
    state.value = false
    dialogVisible.value = true

    request({
        url: '/tienchin/business/summary/' + businessId.value, 
        method: 'get'
    }).then(res => {
        dialogfrom.value = res.data
        console.log(dialogfrom.value)
    })
}
// 修改确定
const updateput = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            request({
                url: '/tienchin/business',
                method: 'put',
                data: dialogfrom.value
            }).then(res => {
                dialogVisible.value = false
                ElMessage({
                    message: '修改成功',
                    type: 'success',
                })
                getTable()
            })
        }
    })
}
// 删除
const deleteGet = () => {
    if (selectedRows.value.length === 0) return

    // 获取所有选中客户姓名
    const names = selectedRows.value.map(item => item.name).join('、')

    ElMessageBox.confirm(
        `是否确认删客户姓名为 "${names}" 的数据项？`,
        '系统提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        let a = dellist.value.join(',')
        request({
            url: '/tienchin/business/' + a,
            method: 'delete'
        }).then(res => {
            ElMessage({
                message: '删除成功',
                type: 'success',
            })
            getTable()
        })
    }).catch(() => {
        // 用户取消，无需处理
    })
}


const handleSizeChange = (val) => {
    pageSize.value = val
    pageNum.value = 1
    getTable()
}

const handleCurrentChange = (val) => {
    pageNum.value = val
    getTable()
}

const handleSelectionChange = (val) => {
    selectedRows.value = val
    if (val.length == 1) {
        businessId.value = val[0].businessId

    } else {
        businessId.value = null
    }
    if (val.length > 0) {
        for (let i = 0; i < val.length; i++) {
            dellist.value.push(val[i].businessId)
        }
    } else {
        dellist.value = []
    }
}

const handleFollow = (row) => {
    console.log('跟进', row)
}

const handleExport = () => {
    // 可根据实际需要传递参数
    request({
        url: '/tienchin/course/export',
        method: 'post',
        data: {
            pageNum: pageNum.value,
            pageSize: pageSize.value
        },
        responseType: 'blob' // 关键：告诉 axios 返回二进制流
    }).then((res:any) => {
        // 创建 blob 对象
        const blob = new Blob([res], { type: 'application/vnd.ms-excel' }) // 或根据后端实际类型调整
        saveAs(blob, "私教课程.xlsx");
    })
}

const assignDialogVisible = ref(false)
const assignForm = ref({
    departmentId: '',
    userId: '',
    deptId: ''
})
const assignFormRef = ref<FormInstance>()
const assignRules = reactive<FormRules<any>>({
    departmentId: [{ required: true, message: '请选择归属部门', trigger: 'change' }],
    userId: [{ required: true, message: '请选择用户', trigger: 'change' }]
})
const deptList = ref<{ label: string; value: string }[]>([]) // 部门下拉
const userList = ref<{ label: string; value: string; deptId: string; userName: string }[]>([]) // 用户下拉

const assignId = ref('')
const type = ref('')

const handleAssign = () => {
    assignFormRef.value?.validate((valid) => {
        if (valid) {
            const selectedUser = userList.value.find(u => u.value === assignForm.value.userId)
            const data = {
                assignId: assignId.value, // businessId
                departmentId: assignForm.value.departmentId, // 归属部门id
                deptId: assignForm.value.deptId,             // 用户所属部门id
                nickName: selectedUser.label,
                type: type.value,
                userId: assignForm.value.userId,
                userName: selectedUser.userName
            }
            request({
                url: '/tienchin/assignment',
                method: 'post',
                data
            }).then(() => {
                assignDialogVisible.value = false
                ElMessage.success('分配成功')
            })
        }
    })
}

const openAssignDialog = (row) => {
    assignForm.value.departmentId = row.deptId ? String(row.deptId) : ''
    assignForm.value.userId = row.userId ? String(row.userId) : ''
    assignDialogVisible.value = true
    getDeptList()
    // 存储 businessId 和 type
    assignId.value = row.businessId
    type.value = row.status // 这里直接用 type 字段名
}

// 示例：获取部门和用户列表
const getDeptList = () => {
    request({ url: '/system/dept/treeselect', method: 'get' }).then(res => {
        deptTree.value = res.data // 直接赋值为树结构
    })
}

const deptTree = ref([])
// el-tree-select 的 props 配置
const deptTreeProps = {
    value: 'id',    // 必须和后端返回的字段一致
    label: 'label',
    children: 'children'
}

const handleDeptChange = (value: string) => {
    assignForm.value.departmentId = value
    request({
        url: `/tienchin/clue/users/${value}`,
        method: 'get'
    }).then((res: any) => {
        userList.value = (res.data || []).map((item: any) => ({
            label: item.nickName,
            value: String(item.userId),
            userName: item.userName,
            deptId: item.deptId
        }));
        assignForm.value.userId = '';
        assignForm.value.deptId = '';
    });
}

const handleUserChange = (userId) => {
    const selectedUser = userList.value.find(u => u.value === userId)
    assignForm.value.deptId = selectedUser.deptId
}

</script>

<style lang="scss" scoped>
.business-container {
    padding: 20px;
}
</style>